package com.jvxb.common.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.jvxb.common.base.entity.WorkResult;
import com.jvxb.common.base.entity.WorkTask;

/**
 * @description 主要作用是在Linux机器上执行命令。
 */
public class WorkTaskUtil {

    public static int WORK_PLATFORM_PORT = 10010;

    public static WorkResult getVersion(String host) {
        if (!IPUtil.isPortUsed(host, WORK_PLATFORM_PORT)) {
            throw new RuntimeException("连接机器异常，请查看机器是否允许连接， 机器ip=" + host);
        }
        HttpRequest post = HttpUtil.createPost("http://" + host + ":" + WORK_PLATFORM_PORT + "/version");
        HttpResponse execute = post.execute();
        WorkResult workResult = JSONObject.parseObject(execute.body(), WorkResult.class);
        return workResult;
    }

    public static String workPlatformUrl(String host, boolean getResult) {
        String url = "http://" + host + ":" + WORK_PLATFORM_PORT + "/execute" + (getResult ? "/result" : "");
        return url;
    }

    public static WorkResult run(WorkTask workTask) {
        return run(workTask, false);
    }

    public static WorkResult runAndGetResult(WorkTask workTask) {
        return run(workTask, true);
    }

    public static WorkResult run(WorkTask workTask, boolean getResult) {
//        System.out.println("机器[" + workTask.getHost() + "]执行命令：\n" + workTask.getCmd());
        if (CommonUtil.isNullOrEmpty(workTask.getHost())) {
            throw new RuntimeException("未指定执行机器");
        }
        if (CommonUtil.isNullOrEmpty(workTask.getCmd())) {
            throw new RuntimeException("未指定执行命令");
        }
        if (!IPUtil.isPortUsed(workTask.getHost(), WORK_PLATFORM_PORT)) {
            throw new RuntimeException("连接机器异常，请查看机器是否允许连接， 机器ip=" + workTask.getHost());
        }
        HttpRequest post = HttpUtil.createPost(workPlatformUrl(workTask.getHost(), getResult));
        post.header("Content-Type", "application/x-www-form-urlencoded");
        post.header("secret", "dbplatform");
        post.body("cmd=" + workTask.getCmd());
        post.setConnectionTimeout(5000);
        post.setReadTimeout(5000);
        HttpResponse execute = post.execute();
        WorkResult workResult = JSONObject.parseObject(execute.body(), WorkResult.class);
        return workResult;
    }
}
